// 首页用户登录注册路由器
//引入express模块
const express = require('express');
//引入数据库连接池模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();

//1.创建用户注册的路由 post /reg(测试成功)
r.post('/reg', (req, res) => {
    var obj = req.body;
    console.log(obj);
    //数据库插入新用户操作
    pool.query('insert into wedding_user set ?', [obj], (err, result) => {
        if (err) res.send({ code: 500, msg: "服务器端错误!" });
        if (result.affectedRows == 0) {
            res.send({ code: 400, msg: "注册失败！" });
        } else {
            res.send({ code: 200, msg: "注册成功！" });
        }
    });
});
//2.用户登录的路由 get /login(测试成功)
r.get('/login', (req, res) => {
    var obj = req.query;
    console.log(obj);
    //接收前台请求时发送的数据用户名和密码
    var _phone = obj.phone;
    var _upwd = obj.upwd;
    //查找数据库
    pool.query('select * from wedding_user where phone = ? and upwd = ?', [_phone, _upwd], (err, result) => {
        if (err) {
            res.send({ code: 500, msg: "服务器端错误!" });
        };
        if (result.length == 0) {
            res.send({ code: 400, msg: "登录失败！" });
        } else {
            res.send({ code: 200, msg: "登录成功！" });
        }
    });
})
// 3.根据用户手机号(登录成功后手机号会存储在sessionStorage中)查询所有用户信息写入页面的路由
r.get('/getInfo', (req, res) => {
    var obj = req.query;
    //接收前台请求时发送的数据用户名和密码
    var _phone = obj.phone;
    //查找数据库
    pool.query('select * from wedding_user where phone = ?', [_phone], (err, result) => {
        if (err) {
            res.send({ code: 500, msg: "服务器端错误!" });
        };
        if (result.length == 0) {
            res.send({ code: 400, msg: "查询失败！" });
        } else {
            res.send(result);
        }
    });
})
// 4.根据手机号查询然后修改用户信息的路由
r.put('/update', (req, res) => {
    var obj = req.body;
    console.log(obj);
    //接收前台请求时发送的数据用户手机号
    var _phone = obj.phone;
    //查找数据库
    var sql = 'update wedding_user set ? where phone = ?'
    pool.query(sql, [obj, _phone], (err, result) => {
        if (err) {
            res.send({ code: 500, msg: "服务器端错误!" });
        } else {
            res.send({ code: 200, msg: "修改成功！" });
        }
    });
})

//导出用户路由模块
module.exports = r;